#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{
    // 1、创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd); //默认读写方式打开
    assert(n != -1);
    (void)n;

#ifdef DEBUG
    cout << "pipefd[0]:" << pipefd[0] << endl;
    cout << "pipefd[1]:" << pipefd[1] << endl;
#endif
    pid_t id = fork();
    assert(id != -1);
    if (!id)
    {
        //子进程
        //建立信道
        close(pipefd[1]);
        char buf[1024];
        while (1)
        {
            ssize_t s = read(pipefd[0], buf, sizeof(buf) - 1);
            if (s > 0)
            {
                //成功
                buf[s] = 0; //内容 + 0
                cout << "child get message [" << getpid() << ']' << "father:" << buf << endl;
            }
        }
        exit(0);
    }
    //父进程
    close(pipefd[0]);
    //写
    string msg = "父进程，传信息中";
    int count = 0;
    char send_buf[1024];
    while (1)
    {
        snprintf(send_buf, sizeof(send_buf), "%s[%d]:%d", msg.c_str(), getpid(), count++);
        write(pipefd[1], send_buf, strlen(send_buf));
        sleep(1);
    }

    pid_t ret = waitpid(id, nullptr, 0);
    assert(ret);
    (void)ret;

    close(pipefd[1]);
}